//
//  JPStatusPictureView.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 16/9/25.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit
import SDWebImage

//  重用标记
private let JPStatusPictureViewCellIdentifier = "JPStatusPictureViewCellIdentifier"

//  每项之间的间距
let itemMargin: CGFloat = 5
//  每项的宽度
let itemWidth = (ScreenWidth - 2 * JPHomeTableViewCellMargin - 2 * itemMargin) / 3


class JPStatusPictureView: UICollectionView {
    
    //  use it when testing, show images's count
    lazy var countLabel: UILabel = {
        
        let label = UILabel(textColor: UIColor.magenta, fontSize: 16)
        return label
    }()
    
    //  it's a array for pictures url string
    var picUrls: [JPStatusPicInfo]? {
        didSet {
            countLabel.text = "\((picUrls?.count)!)"
            
            let size = calSize(picConut: (picUrls?.count)!)
            
            self.snp_updateConstraints { (make) in
                make.size.equalTo(size)
            }
            
            self.reloadData()
        }
    }
    

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
    
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        self.dataSource = self
        self.backgroundColor = UIColor.white
        
        register(JPStatusPicCell.self, forCellWithReuseIdentifier: JPStatusPictureViewCellIdentifier)
        
        addSubview(countLabel)
        
        countLabel.snp_makeConstraints(closure: { (make) in
            make.center.equalTo(self)
        })
    }
    
    //  calculate self size
    private func calSize(picConut: Int) -> CGSize {
        
        if picConut == 1 {
            
            guard let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: picUrls?.first?.thumbnail_pic) else{
                return CGSize.zero
            }
            
            var imageW = image.size.width
            var imageH = image.size.height
            let minImageWidth: CGFloat = 80
            
            if imageW > minImageWidth {
                
                let flowLayout = self.collectionViewLayout as? UICollectionViewFlowLayout
                flowLayout?.itemSize = image.size
                
                return image.size
                
            }else {
                
                imageW = minImageWidth
                imageH = minImageWidth / imageW * imageH
                
                let flowLayout = self.collectionViewLayout as? UICollectionViewFlowLayout
                flowLayout?.itemSize = CGSize(width: imageW, height: imageH)
                
                return CGSize(width: imageW, height: imageH)
            
            }
        }
        //行数
        let rows = picConut > 3 ? 3 : picConut
        //列数
        let cols = (picConut - 1) / 3 + 1
        //视图高度
        let height = CGFloat(cols) * itemWidth + (CGFloat(cols) - 1) * itemMargin
        //视图宽度
        let width = CGFloat(rows) * itemWidth + (CGFloat(rows) - 1) * itemMargin
        
        let flowLayout = self.collectionViewLayout as? UICollectionViewFlowLayout
        flowLayout?.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        return CGSize(width: width, height: height)

    }
}
//  MARK: -- collectionView data souce
extension JPStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate, SDPhotoBrowserDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print(picUrls?.count)
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: JPStatusPictureViewCellIdentifier, for: indexPath) as! JPStatusPicCell
        cell.picUrl = picUrls![indexPath.item]
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = picUrls!.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
        
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        let cell = self.cellForItem(at: IndexPath(item: index, section: 0)) as! JPStatusPicCell
        return cell.imageView.image
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let urlStr = picUrls![index].thumbnail_pic!.replacingOccurrences(of: "thumbnail", with: "bmiddle")
        return URL(string: urlStr)
    }
}

//  MARK: -- DIY collection cell
class JPStatusPicCell: UICollectionViewCell {
    
    var picUrl: JPStatusPicInfo? {
        didSet {
            if let url = picUrl?.thumbnail_pic {
            
                imageView.sd_setImage(with: URL(string: url))
            }
        }
    }
    
    
    lazy var imageView: UIImageView = {
        
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        contentView.addSubview(imageView)
        
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsets.zero)
        }
    }
}
